package com.zy.datareceiver.binsess.decode.service;

import com.zy.datareceiver.binsess.monitoring.entity.MonitoringData;
import com.zy.datareceiver.binsess.monitoring.mapper.MonitoringDataMapper;
import com.zy.datareceiver.core.cast.ConCast;
import com.zy.datareceiver.core.common.SpringApplicationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>实时数据入库线程，对来源于@See {@link StorageTaskService#monitoringDataQueue}
 * 中的数据取出来跟上一次入库的时间做对比，如果数据存储量大于{@link ConCast.DB#DEFAULT_SAVE_MONITOR_SIZE_DB}
 * 或者与上一次的存储时间间隔超过{@link ConCast.Time#MONITORING_DATA_TO_DB_OUT_OF_TIME}
 * 则进行数据存储，一方面保证实时性，一方面避免频繁访问数据库/p>
 * */
public class DBSaveThread extends Thread {
    private static final Logger log = LoggerFactory.getLogger(DBSaveThread.class);
    @Override
    public void run() {
        //正常数据集合
        long now = System.currentTimeMillis();
        List<MonitoringData> dataList = new ArrayList<>(200);
        while(true){
            try {
                MonitoringData monitoringData = StorageTaskService.monitoringDataQueue.take();
                dataList.add(monitoringData);
                if (dataList.size() > ConCast.DB.DEFAULT_SAVE_MONITOR_SIZE_DB ||
                        System.currentTimeMillis() - now > ConCast.Time.MONITORING_DATA_TO_DB_OUT_OF_TIME) {
                    MonitoringDataMapper monitoringDataMapper = SpringApplicationContext.getBean(MonitoringDataMapper.class);
                    monitoringDataMapper.batchInsert(dataList);
                    log.info(" 保存 {} 条实时数据入库", dataList.size());
                    dataList.clear();
                    now = System.currentTimeMillis();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }catch (Exception e){
                log.error("保存数据时出现异常 {}",e);
            }
        }
    }
}
